/*
 * @Author: silence
 * @Date: 2023-03-15 10:20:15
 * @LastEditors: silence silence9685@163.com
 * @LastEditTime: 2023-07-31 15:44:14
 * @Description: 语言国际化
 */

import 'package:get/get.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../../../utils/eventBus/eventBus.dart';
import '../../../utils/sputils/SpUtils.dart';
import '../../../utils/string/StringConstant.dart';
import 'SilLocalizations/SilLocalizations.dart';

// 1获取当前系统语言
// 2app内选择
// 1跟随设备系统语言
// 2选择其他语言
class LanguageController extends GetxController {
  final userSettingLanguage = ''.obs; // 用户将要设置的语言
  static String curSystemLanguageCode = 'en'; // 默认系统语言

  /// 用户设置语言的标识
  static const String USER_SETTED_LANG = "USER_SETTED_LANG";

  /// 语言列表
  Map<String, String> get languageMap {
    return SilLocalizations.languageMap;
  }

  /// 判断后台提示需要中文，还是英文
  bool isPromptEnglish() {
    String? languageStr = this.getCurLanguageStr();
    return (languageStr == '简体中文' || languageStr == '繁體中文') == false;
  }

  /// 当前语言
  String getCurLanguageStr({String? userSettingLanguage}) {
    String? userSetting =
        userSettingLanguage ?? LanguageController.userSettedLang;
    String? key = !SilTools.stringIsEmpty(userSetting)
        ? userSetting
        : LanguageController.curSystemLanguageCode;

    if (SilLocalizations.languageMap.containsKey(key)) {
      return SilLocalizations.languageMap[key] ?? 'English';
    }

    /// 默认英文
    return 'English';
  }

  /// 用户设置的语言，空表示系统跟随
  static String? get userSettedLang {
    return SpUtils.getData(LanguageController.USER_SETTED_LANG);
  }

  /// 用户设置语言
  Future<void> settingLanguage(
    String? language,
  ) async {
    // 用户设置的语言
    String? userSetting = LanguageController.userSettedLang;

    //1 要设置的语言和设置的相同，就是没有改变语言设置,不用处理
    // if (language == userSetting) return;

    //2 用户设置成跟随系统,清空设置
    if (SilTools.stringIsEmpty(language)) {
      if (!SilTools.stringIsEmpty(userSetting)) {
        await SpUtils.remove(LanguageController.USER_SETTED_LANG);
      }
      this.userSettingLanguage.value = language ?? "";
      bus.emit(StringConstant.LanguageChange);
      return;
    }

    //3 用户设置其他语言,更改设置
    this.userSettingLanguage.value = language!;
    await SpUtils.saveData(LanguageController.USER_SETTED_LANG, language);
    bus.emit(StringConstant.LanguageChange);
  }
}
